/**
* <p>Title: commonUtils.java</p>
* <p>Description: 公共utils</p>
* <p>Company: www.huoyunren.com</p>
* @author duanxiangyun
* @date 2015年1月7日
* @version 1.0
*/
package com.duan.test.utils.common;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.WrapsDriver;

import org.apache.commons.codec.binary.Base64;
/**
 * 公共方法
 */
public class CommonUtils {
	
	private static final String injectScript = "injectScript";
	private static final String common_file = "utilities.properties";
	/**
	 * 判断字符串是否为空或者NULL
	 * @param str 字符串
	 * @return Boolean
	 */
	public static Boolean isStrEmpty (String str) {
		if(str == null || str.trim().length() == 0){
		    return true;
		  }
		else {
			return false;
		}
	}
	
	/**
	 * 设置元素的某属性的值
	 * @param element 元素
	 * @param attributeName 属性名
	 * @param value 值
	 */
	public static void setAttribute(WebElement element,
			String attributeName, String value) {
			WrapsDriver wrappedElement = (WrapsDriver) element;
			JavascriptExecutor driver = (JavascriptExecutor)wrappedElement.getWrappedDriver();
			driver.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])", element, attributeName, value);
	}
	
	/**
	 * 高亮元素
	 * @param element 元素
	 */
	public static void highlightElement(WebElement element){
		for (int i = 0; i < 3; i++) {
			WrapsDriver wrappedElement = (WrapsDriver) element;
			JavascriptExecutor driver = (JavascriptExecutor) wrappedElement
			.getWrappedDriver();
			//为元素设置style来高亮
			try {
				driver.executeScript(
				"arguments[0].setAttribute('style',arguments[1]);",
				element, "color: green; border: 2px solid yellow;");
				//取消高亮将style清掉
				Thread.sleep(1000);
				driver.executeScript(
				"arguments[0].setAttribute('style',arguments[1]);",
				element, "");
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 页面元素截图：范围针对元素，可有效降低图片大小，可直接定位问题
	 * @param element
	 * @return File
	 * @throws Exception
	 */
	public static File captureElement(WebElement element,WebDriver driver) throws Exception {
//		WrapsDriver wrapsDriver = (WrapsDriver) element;
		// 截图整个页面
//		File screen = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
		File screen = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
		BufferedImage img = ImageIO.read(screen);
		// 获得元素的高度和宽度
		int width = element.getSize().getWidth();
		int height = element.getSize().getHeight();
		// 创建一个矩形使面上面的高度，和宽度
		Rectangle rect = new Rectangle(width, height);
		// 得到元素的坐标
		Point p = element.getLocation();
		BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width, rect.height);
		//存为png格式
		ImageIO.write(dest, "png", screen);
		return screen;
	}
	/**
	 * 一般截图操作
	 * @param driver webdriver
	 */
	public static void takeScreenShot( WebDriver driver, String imgpath) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
		String mDateTime = formatter.format(new Date());
		String fileName = CommonUtils.getFilePath(imgpath) + mDateTime + ".jpg";
		File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 
        try {
			FileUtils.copyFile(srcFile,new File(fileName));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("Can't save screenshot");
			e.printStackTrace();
		}
	}
	/**
	 * 注入jquery
	 * @param driver webdriver
	 * @param injectStr 注入jquery脚本
	 */
	public static  void injectjQuery(WebDriver driver, String injectStr) {
		JavascriptExecutor jse = (JavascriptExecutor)driver;
		jse.executeScript(injectStr);
	}
	/**
	 * 注入jquery库
	 * @param driver webdriver
	 */
	public static  void injectjQueryIfNeeded(WebDriver driver) {
		JavascriptExecutor jse = (JavascriptExecutor)driver;
		if (!jQueryLoaded(driver)) {
			Properties pro = new Properties();
			try {
				pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(common_file ));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
			jse.executeScript(pro.getProperty(injectScript));
		}
	}
	/**
	 * 判断是已加载jQuery库
	 * @param driver webdriver
	 * @return Boolean
	 */
	public static Boolean jQueryLoaded(WebDriver driver) {
		Boolean loaded;
		JavascriptExecutor jse = (JavascriptExecutor)driver;
		try {
		loaded = (Boolean)jse.executeScript("return " +
		"jQuery()!=null");
		} catch (WebDriverException e) {
		loaded = false;
		}
		return loaded;
	}
//	/**
//	 * 获得文件路径
//	 * @param filePath 项目下文件路径
//	 * @return String
//	 */
//	public static String getFilePath (String filePath) {
//		filePath = filePath.replaceAll("/", "\\\\");
//		URL  urlpath = null;
//		urlpath = CommonUtils.class.getClassLoader().getResource(filePath);
//		if (urlpath == null) {
//			return null;
//		}
//		else {
//			try {
//				return java.net.URLDecoder.decode(urlpath.getPath(),"UTF-8");
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				return urlpath.getPath();
//			}
//		}
//	}
	/**
	 * 组装成文件所在classpath下路径
	 * @param filePath 项目下文件路径
	 * @return String
	 */
	public static String getFilePath (String filePath) {
		URL  urlpath = Thread.currentThread().getContextClassLoader().getResource("");
		String newfilepath = null;
		try {
			newfilepath = java.net.URLDecoder.decode(urlpath.getPath(),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			newfilepath = urlpath.getPath();
		}
		return newfilepath + filePath;
	}
//	/**
//	 * 获得eclips相对路径
//	 * @param filePath 项目下文件路径
//	 * @return String
//	 */
//	public static String getFilePath2 (String filePath) {
//    	String clspath;
//		try {
//			clspath = URLDecoder.decode(currentClsPath,"utf-8");
//			String os = System.getProperty("os.name");  
//			if(os != null &&  os.toLowerCase().startsWith("win")){  
//				clspath = clspath.substring(1, clspath.length());
//			}  
//			else if (os != null && os.toLowerCase().indexOf("linux") > -1) {
//			}			
//			String a = "";
//			if (clspath.contains("/bin/")) {
//				a = clspath.substring(0, clspath.indexOf("/bin"));
//			}
//			else if (clspath.contains("/build/")) {
//				a = clspath.substring(0, clspath.indexOf("/build"));
//			}
//			else {
//				return null;
//			}
//	    	return a + filePath;
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			return null;
//		}	
//	}
	/**
	 * 比较时间先后
	 * @param date1 date1
	 * @param date2 date2
	 * @param dateFormat 期望格式
	 * @return true:date1在date2之前;else:false.
	 */
	public static Boolean isBeforeDate (String date1, String date2, String dateFormat) { 
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.CHINA);
		Date d1 = null;
		Date d2 = null;
		try {
			d1 = sdf.parse(date1);
			d2 = sdf.parse(date2);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return d1.before(d2);
	}
	
	/**
     * 把文本编码为Html代码
     * @param target html代码
     * @return 编码后的字符串
     */
    public static String htmEncode(String target)
    {
        StringBuffer stringbuffer = new StringBuffer();
        int j = target.length();
        for (int i = 0; i < j; i++)
        {
            char c = target.charAt(i);
            switch (c)
            {
            case 60:
                stringbuffer.append("<");
                break;
            case 62:
                stringbuffer.append(">");
                break;
            case 38:
                stringbuffer.append("&");
                break;
            case 34:
                stringbuffer.append("\"");
                break;
            case 169:
                stringbuffer.append("©");
                break;
            case 174:
                stringbuffer.append("®");
                break;
            case 165:
                stringbuffer.append("¥");
                break;
            case 8364:
                stringbuffer.append("€");
                break;
            case 8482:
                stringbuffer.append("™");
                break;
            case 13:
                if (i < j - 1 && target.charAt(i + 1) == 10)
                {
                    stringbuffer.append("<br>");
                    i++;
                }
                break;
            case 32:
                if (i < j - 1 && target.charAt(i + 1) == ' ')
                {
                    stringbuffer.append(" &nbsp;");
                    i++;
                    break;
                }
            default:
                stringbuffer.append(c);
                break;
            }
        }
        return new String(stringbuffer.toString());
    }
    /**
     * time格式转换
     * @param time
     * @return String
     * @throws ParseException
     */
    public static String timeFormatChange (String time, String format1, String format2) throws ParseException {
    	Date date;
    	SimpleDateFormat date1 = new SimpleDateFormat(format1);//"yy-MM-dd HH:mm"
    	date = date1.parse(time);
    	SimpleDateFormat date2 = new SimpleDateFormat(format2);//"yyyy-MM-dd HH:mm:ss"
    	return date2.format(date);
    }
    /**
     * 获得当前时间:yyyy-MM-dd HH:mm:ss
     * @return String
     * @throws ParseException
     */
    public static String getNow () throws ParseException {
    	Date date = new Date();
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//"yy-MM-dd HH:mm"
    	return df.format(date);
    }
    /**
     * 时分秒转为秒数
     * @param timeStr 时间字符串
     * @return int
     */
    public static int HMSToSeconds (String timeStr) {
    	int second = 0;
    	String time = timeStr.replaceAll(" ", "").trim();
    	int temp1;
    	int temp2 = time.indexOf("分");
    	int temp3 = time.indexOf("秒");
    	if (-1 != time.indexOf("小时")) {
    		temp1 = time.indexOf("小时");      	
        	second += Integer.parseInt(time.substring(0, temp1)) * 3600;        	
        	second += Integer.parseInt(time.substring(temp1 + 2, temp2)) * 60;        	
        	second += Integer.parseInt(time.substring(temp2 + 1, temp3));
    	}
    	else {
    		temp1 = time.indexOf("时");
    		if (-1 != temp1) {
        		second += Integer.parseInt(time.substring(0, temp1)) * 3600;
        	}
        	if (-1 != temp2) {
        		if (-1 != temp1) {
        			second += Integer.parseInt(time.substring(temp1 + 1, temp2)) * 60;
        		}
        		else {
        			second += Integer.parseInt(time.substring(0, temp2)) * 60;
        		}
        	}
        	if (-1 != temp3) {
        		if (-1 != temp2) {
        			second += Integer.parseInt(time.substring(temp2 + 1, temp3));
            	}
        		else {
        			second += Integer.parseInt(time.substring(0, temp3));
        		}
        	}
    	}
    	
    	return second;
    }
    
    /** 
     * 计算两个日期之间相差的天数 
     * @param date1 
     * @param date2 
     * @return  int
     * @throws ParseException 
     */  
    public static int daysBetween(String date2,String date1) throws ParseException  
    {  
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar cal = Calendar.getInstance();  
        cal.setTime(df.parse(date1));  
        long time1 = cal.getTimeInMillis();               
        cal.setTime(df.parse(date2)); 
        long time2 = cal.getTimeInMillis();       
        double between_days=Math.ceil((double)(time2-time1)/(1000*3600*24));  
       return (new Double(between_days)).intValue();         
    } 
    
    /**
     * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
     * @param imgFile 图片地址
     * @return 图片文件转成的Base64编码
     */
    public static String GetImageStr(String imgFile)
    {
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try 
        {
            in = new FileInputStream(imgFile);        
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        Base64 encoder = new Base64();
        return encoder.encodeAsString(data);//返回Base64编码过的字节数组字符串
    } 
    
	/**
	 * 取当前时间
	 * @param timestamp 时间格式
	 * @return
	 */
	public static String now(String timestamp) {
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat(timestamp);
		return sdf.format(d);
	}

	/**
	 * 返回当前时间前/后多少秒/天/年/月等
	 * 
	 * @param timestamp
	 *            返回时间格式
	 * @param interval
	 *            时间间隔
	 * @param calendarType
	 *            calender的时间类型 如Calender.Minute
	 * @return
	 */
	public static String nowBeforeOrAfter(String timestamp, String interval,
			String calendarType) {
		SimpleDateFormat sdf = new SimpleDateFormat(timestamp);
		Calendar calender = Calendar.getInstance();
		calender.add(Integer.parseInt(calendarType), Integer.parseInt(interval));
		return sdf.format(calender.getTime());
	}

	/**
	 * 返回某时间前/后多少秒/天/年/月等
	 * @param time 
	 * @param timestamp
	 *            返回时间格式
	 * @param interval
	 *            时间间隔
	 * @param calendarType
	 *            calender的时间类型 如Calender.Minute
	 * @return
	 * @throws ParseException 
	 */
	public static String getTimeBeforeOrAfter(String time, String timestamp, String interval,
			String calendarType) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(timestamp);
		Calendar calender = Calendar.getInstance();
		calender.setTime(sdf.parse(time));
		calender.add(Integer.parseInt(calendarType), Integer.parseInt(interval));
		return sdf.format(calender.getTime());
	}
	/**
	 * 获得昨天的0点
	 * 
	 * @return String
	 */
	public static String yesterDayStart() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		String sd = sdf.format(new Date(new Date().getTime() - 24 * 60 * 60
				* 1000));
		return sd;
	}

	/**
	 * 获得昨天的23点59粉59秒
	 * 
	 * @return String
	 */
	public static String yesterDayEnd() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
		String sd = sdf.format(new Date(new Date().getTime() - 24 * 60 * 60
				* 1000));
		return sd;
	}

	/**
	 * 获得当前时间
	 * 
	 * @return String
	 */
	public static String now() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sd = sdf.format(new Date(new Date().getTime()));
		return sd;
	}

	/**
	 * 获得当天的0点0粉0秒
	 * 
	 * @return String
	 */
	public static String todayStart() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		String sd = sdf.format(new Date(new Date().getTime()));
		return sd;
	}

	/**
	 * 获得第二天的0点0粉0秒
	 * 
	 * @return String
	 */
	public static String todayEnd() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
		String sd = sdf.format(new Date(new Date().getTime()));
		return sd;
	}

	/**
	 * 获得当前时间的前几天
	 * 
	 * @param lastInt
	 *            前几天
	 * @return String
	 */
	public static String nowBeforeDays(String lastInt) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sd = sdf.format(new Date(new Date().getTime() - Integer.parseInt(lastInt) * 24
				* 60 * 60 * 1000));
		return sd;
	}

	/**
	 * 获得当前时间的后几天
	 * 
	 * @param afterInt
	 *            后几天
	 * @return String
	 */
	public static String nowAfterDays(String afterInt) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sd = sdf.format(new Date(new Date().getTime() + Integer.parseInt(afterInt) * 24
				* 60 * 60 * 1000));
		return sd;
	}
	/**
	 * 将字符串转换成MD5编码
	 * 
	 * @param inStr
	 * @return String
	 */
	public static String string2MD5(String inStr) {
		String re_md5 = new String();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(inStr.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

			re_md5 = buf.toString().toUpperCase();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return re_md5;
	}
	/**
	 * 获取1分鐘前日期字符串
	 * 
	 * @return String
	 */
	public static String GetDateString() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MINUTE, -1);
		long date = cal.getTime().getTime();
		SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return matter.format(date);
	}
	/**
	 * 比较time2与time1时间间隔,精确到s
	 * 
	 * @param fstTime
	 *            time1
	 * @param sndTime
	 *            time2
	 * @param timestamp
	 *            时间格式
	 * @return
	 */
	public static long getTimeDif(String fstTime, String sndTime,
			String timestamp) {
		DateFormat df = new SimpleDateFormat(timestamp);
		long diff = 0;
		try {
			Date d1 = df.parse(fstTime);
			Date d2 = df.parse(sndTime);
			diff = Math.abs((d2.getTime() - d1.getTime()) / 1000);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return diff;
	}
	  /**
	   * 获得当前时间的前几天
	   * 
	   * @param lastInt
	   *            前几天
	   * @return String
	   */
	  public static String nowBeforeOrAfterStart(String timestamp, String interval,
	      String calendarType,int hour,int min,int sec) {
	    SimpleDateFormat sdf = new SimpleDateFormat(timestamp);
	    Calendar calender = Calendar.getInstance();
	    calender.add(Integer.parseInt(calendarType), Integer.parseInt(interval));
	    calender.set(Calendar.HOUR_OF_DAY, hour);  
	    calender.set(Calendar.MINUTE, min);   
	    calender.set(Calendar.SECOND,sec); 
	    return sdf.format(calender.getTime());
	  }
	    /**
	     * 获得昨天的0点
	     * @return String
	     */
	    public static String getYesterDayStart () {
	    	SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd 00:00:00");
			String sd = sdf.format(new Date(new Date().getTime()-24*60*60*1000));
			return sd;
	    }
	    /**
	     * 获得昨天的23点59粉59秒
	     * @return String
	     */
	    public static String getYesterDayEnd () {
	    	SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd 23:59:59");
			String sd = sdf.format(new Date(new Date().getTime()-24*60*60*1000));
			return sd;
	    }
}
